package com.wiz.data.vo.to;

import java.nio.charset.Charset;

import com.google.common.primitives.Bytes;
import com.wiz.data.util.HexUtil;

/**
 * 带长度的域
 * @author Hakeny
 */
public class MessageLengthStringFiled extends MessageFiled {

	@Override
	public byte[] toBytes() {
		byte[] bs = ((String)value).getBytes(Charset.forName("UTF-8"));
		int length =  bs.length;
		byte[] b = new byte[4];  
		b[0] = (byte) (0xff & length);  
	    b[1] = (byte) ((0xff00 & length) >> 8);  
	    b[2] = (byte) ((0xff0000 & length) >> 16);  
	    b[3] = (byte) ((0xff000000 & length) >> 24);  
		return Bytes.concat(b,bs);
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		MessageLengthStringFiled filed = (MessageLengthStringFiled) super.clone();
		filed.setType(this.type);
//		filed.setValue(this.value);
		filed.setNeedLength(this.needLength);
		return filed;
	}

	public static void main(String[] args) {
		String value = "aaa";
		byte[] bs = ((String)value).getBytes(Charset.forName("UTF-8"));
		int length =  bs.length;
		byte[] b = new byte[4];  
		b[0] = (byte) (0xff & length);  
	    b[1] = (byte) ((0xff00 & length) >> 8);  
	    b[2] = (byte) ((0xff0000 & length) >> 16);  
	    b[3] = (byte) ((0xff000000 & length) >> 24);  
	    byte[] total = Bytes.concat(b,bs);
	    System.out.println(HexUtil.Bytes2HexString(total));
	    
	    int number = total[0] & 0xFF;  
	    // "|="按位或赋值。  
	    number |= ((total[1] << 8) & 0xFF00);  
	    number |= ((total[2] << 16) & 0xFF0000);  
	    number |= ((total[3] << 24) & 0xFF000000);  
	    
	    byte[] nbs = new byte[number];
	    for(int i=0;i<number;i++){
	    	nbs[i] = total[i+4];
	    }
	    System.out.println(new String(nbs));
	}
}
